import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Select, Space, Divider } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { PlusOutlined } from '@ant-design/icons';
import { useUser } from '../../contexts/UserContext';
import { IArticle } from '../../types';

const { TextArea } = Input;
const { Option } = Select;

// 预设标签选项
const tagOptions = ['React', '前端', 'TypeScript', 'JavaScript', '教程', '性能优化', '最佳实践'];

const ArticleEditor: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const { user } = useUser();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [newTag, setNewTag] = useState('');
    const [tags, setTags] = useState<string[]>(tagOptions);

    useEffect(() => {
        if (id) {
            // 如果是编辑模式，加载文章数据
            const mockArticle: IArticle = {
                id: '1',
                title: 'React 18新特性详解',
                content: '# React 18新特性详解\n\n## 1. 自动批处理\n\nReact 18 中新增了自动批处理...',
                author: {
                    id: '1',
                    username: 'admin',
                    avatar: 'https://joeschmoe.io/api/v1/random'
                },
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
                likes: 128,
                comments: 32,
                tags: ['React', '前端']
            };
            form.setFieldsValue(mockArticle);
        }
    }, [id, form]);

    const onFinish = async (values: any) => {
        if (!user) {
            message.error('请先登录！');
            return;
        }

        if (!values.tags || values.tags.length === 0) {
            message.error('请至少选择一个标签！');
            return;
        }

        setLoading(true);
        try {
            // TODO: 调用API保存文章
            message.success(id ? '文章更新成功！' : '文章发布成功！');
            navigate('/articles');
        } catch (error) {
            message.error('操作失败，请重试！');
        } finally {
            setLoading(false);
        }
    };

    const addTag = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            if (newTag && !tags.includes(newTag)) {
                setTags([...tags, newTag]);
                setNewTag('');
            }
        }
    };

    return (
        <Card title={id ? '编辑文章' : '写文章'}>
            <Form
                form={form}
                layout="vertical"
                onFinish={onFinish}
            >
                <Form.Item
                    name="title"
                    label="标题"
                    rules={[{ required: true, message: '请输入文章标题！' }]}
                >
                    <Input placeholder="请输入文章标题" />
                </Form.Item>

                <Form.Item
                    name="tags"
                    label="标签"
                    rules={[{ required: true, message: '请至少选择一个标签！' }]}
                >
                    <Select
                        mode="multiple"
                        placeholder="请选择标签"
                        dropdownRender={menu => (
                            <>
                                {menu}
                                <Divider style={{ margin: '8px 0' }} />
                                <Space style={{ padding: '0 8px 4px' }}>
                                    <Input
                                        placeholder="输入新标签"
                                        value={newTag}
                                        onChange={e => setNewTag(e.target.value)}
                                        onKeyDown={addTag}
                                    />
                                    <Button
                                        type="text"
                                        icon={<PlusOutlined />}
                                        onClick={() => {
                                            if (newTag && !tags.includes(newTag)) {
                                                setTags([...tags, newTag]);
                                                setNewTag('');
                                            }
                                        }}
                                    >
                                        添加
                                    </Button>
                                </Space>
                            </>
                        )}
                    >
                        {tags.map(tag => (
                            <Option key={tag} value={tag}>{tag}</Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    name="content"
                    label="内容"
                    rules={[{ required: true, message: '请输入文章内容！' }]}
                >
                    <TextArea
                        rows={15}
                        placeholder="请输入文章内容（支持Markdown格式）"
                    />
                </Form.Item>

                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            {id ? '更新' : '发布'}
                        </Button>
                        <Button onClick={() => navigate('/articles')}>
                            取消
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default ArticleEditor; 